go to previous page   go to home page   go to next page

Answer:

The listener must coordinate the button's action command sends with what is done. Copy this program and run it. It is the start for many of the programming exercises for this chapter.


Corrected actionPerformed()

Here is the complete program:

import java.awt.*; 
import java.awt.event.*;
import javax.swing.*; 

public class TwoButtons extends JFrame implements ActionListener
{
  JButton redButton ;
  JButton grnButton ;

  // constructor for TwoButtons
  public TwoButtons(String title)                           
  {
    super( title );
    
    redButton = new JButton("Red");
    grnButton = new JButton("Green");
    redButton.setActionCommand( "red" );   // set the  command 
    grnButton.setActionCommand( "green" ); // set the  command   

    // register the buttonDemo frame
    // as the listener for both Buttons.
    redButton.addActionListener( this );
    grnButton.addActionListener( this );     

    setLayout( new FlowLayout() ); 
    add( redButton );                      
    add( grnButton );
    
    setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );   
  }

  public void actionPerformed( ActionEvent evt)
  {
    // check which command has been sent
    if ( evt.getActionCommand().equals( "red" ) )
      getContentPane().setBackground(  Color.red  );    
    else 
      getContentPane().setBackground( Color.green );    

    repaint();
  }

  public static void main ( String[] args )
  {
    TwoButtons demo  = new TwoButtons( "Click a Button" ) ;
    
    demo.setSize( 200, 150 );     
    demo.setVisible( true );      
  }
}

QUESTION 13:

Imagine that you want an icon (a little picture) to appear on each button rather than text. Will this cause problems for actionPerformed()?